package com.leeall.spring.utils;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Spring Context Loader,create and manage java beans
 * 
 * @author Leeall (lixiaosong@gmail.com)
 * 
 */
public class SpringContextLoader {

    /**
     * Log4j Logger
     */
    private static Logger logger = Logger.getLogger(SpringContextLoader.class);
    private static ApplicationContext ctx;

    static {
        logger.info("OK,Let us begin to Load the context...");
        init();
    }

    public SpringContextLoader() {
        super();
    }

    /**
     * A monk method,just call the clazz's statis method.
     */
    public static void monk() {

    }

    /**
     * Init the context
     * @return init status
     */
    public static synchronized boolean init() {
        try {
            ApplicationContext tmpCxt = new ClassPathXmlApplicationContext(
                    "applicationContext.xml");
            if (tmpCxt != null) {
                ctx = tmpCxt;
                logger.info("OK,The services have been loaded successfully!");
                return true;
            } else {
                logger.error("Oh!Some Errors when The services try to load.");
                return false;
            }
        } catch (Exception e) {
            logger.error("Init context error:", e);
        }
        return false;
    }

    /**
     * Reload the spring context
     * @return status
     */
    public synchronized static boolean reload() {
        logger.info("OK,Let us begin to reLoad the context...");
        return init();
    }

    /**
     * Get Bean from spring context
     */
    public static Object getBean(String beanName) throws Exception {
        try {
            if (ctx.containsBeanDefinition(beanName)) {
                return ctx.getBean(beanName);
            } else {
                throw new Exception("Context doesn't contain bean: " + beanName);
            }
        } catch (Exception e) {
            logger.error("Get Bean " + beanName + " Failed: ", e);
            throw new Exception("Get Bean " + beanName + " Failed: ", e);
        } finally {
        }
    }
}
